using System;
using System.IO;
using System.Xml;
using Microsoft.SPOT;

namespace GadgeteerLibrary
{
    public static class ConfigurationManager
    {
        /// <summary>
        /// Reads the configuration file of the device which can be downloaded from the web site
        /// </summary>
        /// <param name="xmlStream">Instance of the FileStream of the configuration file</param>
        /// <returns>Returns an instance of the class AppSettings containing necessary device information which will be used in the sensor registration</returns>
        public static AppSettings ReadConfiguration(FileStream xmlStream)
        {
            try
            {
                AppSettings appSettings = new AppSettings();

                using (XmlReader reader = XmlReader.Create(xmlStream))
                {
                    reader.MoveToContent();
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            switch (reader.Name)
                            {
                                case "User_id":
                                    reader.Read();
                                    appSettings.UserID = reader.Value;
                                    break;
                                case "Id":
                                    reader.Read();
                                    appSettings.DeviceID = reader.Value;
                                    break;
                                case "APIKey":
                                    reader.Read();
                                    appSettings.APIKey = reader.Value;
                                    break;
                                case "Name":
                                    reader.Read();
                                    appSettings.DeviceName = reader.Value;
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }

                return appSettings;
            }
            catch (XmlException xe)
            {
                Debug.Print(xe.Message);
                return null;
            }
        }
    }
}
